import React, {memo, useEffect, useState} from 'react';

import './quanlityControl.css';
import {FluorescenceCanvas, FluorescenceEntity} from "../../../../../common/canvas";
import {WELLS_COLUMN, WELLS_ROW} from "../../../plate/config";
import {DATA_ANALYSIS_METHOD} from "../quantification/config";
import {useDispatch, useSelector} from "react-redux";
import Title from "../../../../../components/Title/Title";
import Slider from "../../../../../components/slider/Slider";
import {deepClone} from "../../../../../common/utils";
import {saveData} from "../../../store/actionCreators";
import {useDebounce} from "../../../../../common/myHooks";
import {WELL_TYPE} from "../../../store/constants";
import QcTable from "../../../../../components/qcTable/QcTable";
import {saveFailureReport} from "./store/actionCreators";

export default memo(function QuanlityControl() {
  const dispatch = useDispatch();
  const {
    data,
    pcrAllCycle,
    analysisShowLineArr,
    targetSelectedArr,
    dataAnalysisMethod,
    failureReport,
    isCN
  } = useSelector(
    state => ({
      data: state.dataReducer.data,
      analysisShowLineArr: state.plateReducer.analysisShowLineArr,  //  包含可以画线的well(同时有target和sampleName)
      targetSelectedArr: state.quantificationReducer.targetSelectedArr, //  保存Target Setting中Opt被选中的target的name
      dataAnalysisMethod: state.quantificationReducer.dataAnalysisMethod,  //  分析的方法(3种)
      pcrAllCycle: state.protocolReducer.pcrAllCycle,
      failureReport:state.quanlityControlReducer.failureReport,
      isCN: state.languageReducer.isCN
    }));
  const [failReport, setFailReport] = useState([]);
  const quantificationStyle = {
    paddingLeft: 60,
    paddingTop: 10,
    paddingBottom: 50,
    paddingRight: 10,
    dataPaddingLeft: 40,
    dataPaddingBottom: 40,
    dataPaddingTop: 40,
    dataPaddingRight: 40,
    axisTitleLeft: "RFU(10^3)",
    axisTitleLeftPadding: 30,
    axisTitleBottom: "Cycles",
    axisTitleBottomPadding: 20,
    maxX: pcrAllCycle,
    xDataStart: 1
  };
  let cloneData = {};

  useEffect(() => {
    let quantificationCurve = FluorescenceCanvas.init("quantification", quantificationStyle);
    analysisShowLineArr.forEach(item => {
      if (item.omit.value === "true" || !data.wells[item.id].show || !targetSelectedArr.includes(item.target.value)) {
        return;
      }
      quantificationCurve.addEntity(FluorescenceEntity.getInstance({
        id: item.id,
        dataList: data.wells[item.id].lines[item.channelIndex][DATA_ANALYSIS_METHOD[dataAnalysisMethod]],
        color: item.color,
        text: WELLS_ROW[item.row] + WELLS_COLUMN[item.col]
      }));
    });
    return () => {
      quantificationCurve.destroyCanvas();
    };
  }, [analysisShowLineArr]);

  useEffect(() => {
    let failArr = analysisShowLineArr.map(item => {
        return {
          well: item.well.value,
          neg: item.task.value === WELL_TYPE.NEG && (item.cq.value < data.quanlityControl?.negCq),
          ntc: item.task.value === WELL_TYPE.NTC && (item.cq.value < data.quanlityControl?.ntcCq),
          pos: item.task.value === WELL_TYPE.POS && (item.cq.value > data.quanlityControl?.posCq || item.cq.value === "NA"),
          std: item.task.value === WELL_TYPE.STD && item.cq.value === "NA",
          eff: item.task.value === WELL_TYPE.STD
            && (parseInt(item.quantityEfficiency.value) < data.quanlityControl?.efficiency.min
              || parseInt(item.quantityEfficiency.value) > data.quanlityControl?.efficiency.max
              || item.quantityEfficiency.value === "NA"),
          r2: item.task.value === WELL_TYPE.STD && (item.r.value < data.quanlityControl?.stdCurveR2 || item.r.value === "NA"),
          rdev: item.cqSd.value > data.quanlityControl?.cqStdDev
        };
      }
    );
    setFailReport(failArr);
    dispatch(saveFailureReport(failArr));
  }, [data]);

  const getNEG = useDebounce(value => {
    cloneData = deepClone(data, cloneData);
    cloneData.quanlityControl.negCq = value;
    dispatch(saveData(cloneData));
  }, 200);

  const getNTC = useDebounce(value => {
    cloneData = deepClone(data, cloneData);
    cloneData.quanlityControl.ntcCq = value;
    dispatch(saveData(cloneData));
  }, 200);

  const getPOS = useDebounce(value => {
    cloneData = deepClone(data, cloneData);
    cloneData.quanlityControl.posCq = value;
    dispatch(saveData(cloneData));
  }, 200);

  const getEfficiency = useDebounce(value => {
    cloneData = deepClone(data, cloneData);
    cloneData.quanlityControl.efficiency = value;
    dispatch(saveData(cloneData));
  }, 200);

  const getR2 = useDebounce(value => {
    cloneData = deepClone(data, cloneData);
    cloneData.quanlityControl.stdCurveR2 = value / 100;
    dispatch(saveData(cloneData));
  }, 200);

  const getDev = useDebounce(value => {
    cloneData = deepClone(data, cloneData);
    cloneData.quanlityControl.cqStdDev = value / 100;
    dispatch(saveData(cloneData));
  }, 200);

  return (
    <div className="quanlityControl">
      <section className="quanlityControlTop">
        <div>
          <div>{isCN ? "标记布局" : "Flag Layout"}</div>
          <QcTable/>
        </div>
        <div>
          <div>{isCN ? "质控报告" : "Failure Report"}</div>
          <div className="scrollBarStyle QCTable">
            <ul>
              <li>Well</li>
              <li>NEG</li>
              <li>NTC</li>
              <li>POS</li>
              <li>STD</li>
              <li>EFF</li>
              <li>R2</li>
              <li>RDEV</li>
            </ul>
            <section className="scrollBarStyle">
              {
                failReport.map((item, index) => (
                    <ul className="failureReportPic" key={index}>
                      <li>{item.well}</li>
                      <li>{item.neg ? <div/> : null}</li>
                      <li>{item.ntc ? <div/> : null}</li>
                      <li>{item.pos ? <div/> : null}</li>
                      <li>{item.std ? <div/> : null}</li>
                      <li>{item.eff ? <div/> : null}</li>
                      <li>{item.r2 ? <div/> : null}</li>
                      <li>{item.rdev ? <div/> : null}</li>
                    </ul>
                  )
                )
              }
            </section>
          </div>
        </div>
      </section>
      <section className="quanlityControlBottom">
        <div>
          <Title name={isCN ? "质控设置" : "Quality Control Setting"}/>
          <ul>
            <li>
              <Slider name={isCN ? "NEG（阴性对照）Cq" : "NEG (Negative Control) Cq"} max={50} defaultShowValue={data.quanlityControl?.negCq || 38}
                      getValue={getNEG}/>
            </li>
            <li>
              <Slider name={isCN ? "NTC(无模板对照)Cq" : "NTC (No Template Control) Cq"} max={50} defaultShowValue={data.quanlityControl?.ntcCq || 38}
                      getValue={getNTC}/>
            </li>
            <li>
              <Slider name={isCN ? "POS(阳性对照)Cq" : "POS (Positive Control) Cq"} max={50} defaultShowValue={data.quanlityControl?.posCq || 35}
                      reverse getValue={getPOS}/>
            </li>
            <li>
              <Slider name={isCN ? "标准品无Cq值" : "Standard without a Cq"} reverse firstType/>
            </li>
            <li>
              <Slider name={isCN ? "扩增效率" : "Efficiency"} efficiencyValue={data.quanlityControl.efficiency} secondType
                      getValue={getEfficiency}/>
            </li>
            <li>
              <Slider name={isCN ? "标准曲线R2" : "Std Curve R2"} max={100}
                      defaultShowValue={data.quanlityControl ? data.quanlityControl.stdCurveR2 * 100 : 98} dec
                      getValue={getR2}/>
            </li>
            <li>
              <Slider name={isCN ? "Cq SD" : "Replicate group Cq Std Dev"} max={100}
                      defaultShowValue={data.quanlityControl ? data.quanlityControl.cqStdDev * 100 : 50} dec reverse
                      getValue={getDev}/>
            </li>
            <li>
              <div>
                <div style={{backgroundColor: "#d01935"}}/>
                <span>{isCN ? "失败" : "Fail"}</span>
              </div>
              <div>
                <div style={{backgroundColor: "#50e33c"}}/>
                <span>{isCN ? "通过" : "Pass"}</span>
              </div>
            </li>
          </ul>
        </div>
        <div className="scrollBarStyle">
          <section style={{width: "100%", height: "100%"}} id="quantification"/>
        </div>
      </section>
    </div>
  );
});